import './Annex.scss'

import dayjs from 'dayjs'

import { Column } from '@ant-design/plots'
import { Empty, Spin, Pagination } from 'antd'
import { useRef, useState, useEffect } from 'react'
import { useEventEmitter, useMount, useRequest, useSize } from 'ahooks'

import { FrontModalBox } from '../Modal'
import { TableList } from '../Modal/TableList'
import { TitleSmall001 } from '../Common/SmallTitle'
import { Http } from '../../../../Common/Api'
import { TextList001 } from '../Common/TextList'
import { ICON } from '../../../../Common/Configure/Icon'
import { singularColumnTemplate } from '../Common/AssetsCharts'

export const AnnexA01 = ({ InfoTypeManageUuid }) => {
    const [data, setData] = useState()
    const Box = useRef()
    const size = useSize(Box)

    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const result = Object.values(
                res.list.reduce((acc, obj) => {
                    const key = obj.infoTypeManageUuid
                    if (!acc[key]) acc[key] = { uuid: key, label: obj.infoTypeManageName.split('-').at(-1), 数量: 0 }
                    acc[key].数量++
                    return acc
                }, {}),
            )
            setData(result)
        },
    })

    useMount(() => {
        runAsync({ url: 'getInfoManage', data: { InfoTypeManageUuid } })
    })

    const [OptionsCall, setOptionsCall] = useState()

    return (
        <div className="AnnexA01">
            {data ? (
                data.length !== 0 ? (
                    <div className="Box" ref={Box}>
                        {size && (
                            <Column
                                {...singularColumnTemplate({ size, data, yField: '数量', color: '#B2FBFD' })}
                                onReady={plot =>
                                    plot.on('plot:click', e => {
                                        const { x, y } = e
                                        const [{ data }] = plot.chart.getTooltipItems({ x, y })
                                        setOptionsCall({
                                            type: 'TableList',
                                            data: {
                                                title: `${data.label}列表`,
                                                type: 'securitySlopeLeft',
                                                uuid: data.uuid,
                                            },
                                        })
                                    })
                                }
                            />
                        )}
                    </div>
                ) : (
                    <Empty />
                )
            ) : (
                <Spin />
            )}
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const AnnexA02 = ({ top, InfoTypeManageUuid, org, time }) => {
    const [Data, setData] = useState()
    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setData(res.list) })
    const Top = [
        { uuid: 1, label: '文件名称', value: 'tableName', flex: 3 },
        { uuid: 2, label: '上传时间', value: 'eventDate', flex: 1, time },
    ]

    useMount(() => {
        runAsync({
            url: 'getInfoManage',
            data: {
                InfoTypeManageUuid,
                OEventDate: 'desc',
                organizationUuid: org || '',
                pageIndex: 1,
                pageSize: 10000,
            },
        })
    })
    const [OptionsCall, setOptionsCall] = useState()
    const TextEvent = useEventEmitter()
    TextEvent.useSubscription(val =>
        setOptionsCall({ type: 'AnnexA02', data: { uuid: val.uuid, title: val.tableName } }),
    )

    return (
        <div className="AnnexA02">
            {Data ? (
                Data.length !== 0 ? (
                    <div className="Box">
                        <TextList001 Top={top || Top} data={Data} click={TextEvent} />
                    </div>
                ) : (
                    <Empty />
                )
            ) : (
                <Spin />
            )}
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const AnnexA03 = ({ InfoTypeManageUuid }) => {
    const [pageIndex, setPageIndex] = useState(1)
    const [Data, setData] = useState()
    const [Total, setTotal] = useState(0)

    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setData(res.list)
            setTotal(res.total)
        },
    })

    useEffect(() => {
        runAsync({ url: 'getInfoManage', data: { InfoTypeManageUuid, pageIndex, pageSize: 10, OEventDate: 'asc@0' } })
    }, [runAsync, pageIndex, InfoTypeManageUuid])

    const [OptionsCall, setOptionsCall] = useState()

    return (
        <div className="AnnexA03">
            {Data ? (
                Data.length !== 0 ? (
                    <div className="Box">
                        <div className="List">
                            {Data.map(({ uuid, tableName, eventDate }) => (
                                <div
                                    key={uuid}
                                    onClick={() => {
                                        setOptionsCall({
                                            type: 'AnnexA02',
                                            data: { uuid, title: tableName },
                                        })
                                    }}
                                >
                                    <div>{tableName}</div>
                                    <div>{eventDate}</div>
                                </div>
                            ))}
                        </div>
                        <div className="Pagination">
                            <Pagination
                                showSizeChanger={false}
                                showTotal={total => `共${total}条记录 -- 当前第${pageIndex}页`}
                                defaultCurrent={1}
                                total={Total}
                                onChange={setPageIndex}
                            />
                        </div>
                    </div>
                ) : (
                    <Empty />
                )
            ) : (
                <Spin />
            )}
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const AnnexA04 = ({ ParentUuid }) => {
    const [Data, setData] = useState()
    const [Details, setDetails] = useState([])
    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setData(res[0].children || []) })
    useMount(() => {
        runAsync({ url: 'getInfoTypeManage', data: { ParentUuid } })
    })

    const { runAsync: getDetails } = useRequest(Http, {
        manual: true,
        onSuccess: (res, params) => {
            const [{ data }] = params
            const { InfoTypeManageUuid: uuid } = data
            setDetails([...Details, { uuid, data: res.list }])
        },
    })

    const onGetDetails = uuid => {
        if (!Details.some(v => v.uuid.includes(uuid)))
            getDetails({ url: 'getInfoManage', data: { InfoTypeManageUuid: uuid, OEventDate: 'asc@0' } })
    }

    return (
        <div className="AnnexA04">
            {Data ? (
                Data.length !== 0 ? (
                    <div className="Box">
                        {(() => {
                            const halfLength = Math.ceil(Data.length / 2)
                            const A01 = Data.slice(0, halfLength)
                            const A02 = Data.slice(halfLength)
                            const List = [A01, A02]
                            return List.map((item, index) => (
                                <div className="List" key={index}>
                                    {item.map(({ uuid, tableName }) => (
                                        <div key={uuid}>
                                            <div className="Item" onClick={() => onGetDetails(uuid)}>
                                                {ICON['wenjianjia']} {tableName}
                                            </div>
                                            {Details.some(v => v.uuid.includes(uuid)) && (
                                                <div className="Child">
                                                    {Details.find(v => v.uuid === uuid).data.map(
                                                        ({ uuid, tableName, eventDate }) => (
                                                            <div key={uuid}>
                                                                <div>{tableName}</div>
                                                                <div>{eventDate}</div>
                                                            </div>
                                                        ),
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            ))
                        })()}
                    </div>
                ) : (
                    <Empty />
                )
            ) : (
                <Spin />
            )}
        </div>
    )
}

export const AnnexA05 = ({ performanceType }) => {
    const [Data, setData] = useState()
    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setData(res) })

    const Top = [
        { uuid: 1, label: '排名', value: 'sortId', flex: 1 },
        { uuid: 2, label: '单位名称', value: 'tableName', flex: 5 },
        { uuid: 3, label: '分数', value: 'score', flex: 1 },
    ]

    useMount(() => {
        runAsync({
            url: 'getPerformancesRankByPerformanceType',
            data: { performanceType, yearMonth: dayjs().format('YYYY-MM') },
        })
    })

    return (
        <div className="AnnexA05">
            {Data ? (
                Data.length !== 0 ? (
                    <div className="Box">
                        <TextList001 Top={Top} data={Data} />
                    </div>
                ) : (
                    <Empty />
                )
            ) : (
                <Spin />
            )}
        </div>
    )
}

export const AnnexA06 = () => {
    // getContracts
    return (
        <div className="AnnexA06">
            <TableList data={{ title: '', type: 'ContractListA01' }} />
        </div>
    )
}

export const AnnexA07 = ({ title, seat, InfoTypeManageUuid }) => {
    const [Data, setData] = useState([])
    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setData(res.list) })
    useMount(() => {
        runAsync({
            url: 'getInfoManage',
            data: { InfoTypeManageUuid, pageIndex: 1, pageSize: 10000, OEventDate: 'asc@0' },
        })
    })

    const [OptionsCall, setOptionsCall] = useState()

    return (
        <div className={`AnnexA07 ${seat}`}>
            <div className="AnnexA07__Title">{title}</div>
            <div className="AnnexA07__List">
                {Data.map(({ uuid, tableName }) => (
                    <div
                        key={uuid}
                        onClick={() => setOptionsCall({ type: 'AnnexA02', data: { uuid: uuid, title: tableName } })}
                    >
                        {tableName}
                    </div>
                ))}
            </div>
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const AnnexA08 = ({ title, InfoTypeManageUuid }) => {
    const [Data, setData] = useState()
    const [OptionsCall, setOptionsCall] = useState()
    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setData(res.list) })
    useMount(() => {
        runAsync({
            url: 'getInfoManage',
            data: { InfoTypeManageUuid, pageIndex: 1, pageSize: 10000, OEventDate: 'asc@0' },
        })
    })

    return (
        <div className="AnnexA08">
            <TitleSmall001 title={title} />
            {Data ? (
                Data.length !== 0 ? (
                    <div className="AnnexA08_List">
                        {Data.map(({ uuid, tableName }) => (
                            <div
                                key={uuid}
                                onClick={() => setOptionsCall({ type: 'AnnexA02', data: { uuid, title: tableName } })}
                            >
                                <div>{tableName}</div>
                                <div>查看</div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <Empty />
                )
            ) : (
                <Spin />
            )}

            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const AnnexA09 = ({ uuidArr }) => {
    const [Data, setData] = useState()
    const [OptionsCall, setOptionsCall] = useState()

    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setData(res) })

    useMount(() => {
        runAsync({ url: 'getInfoTypeManage' })
    })

    return (
        <div className="AnnexA09">
            {Data ? (
                Data.length !== 0 ? (
                    <div className="AnnexA09_List">
                        {Data.map(({ uuid, tableName, children }) => {
                            if (uuidArr.includes(uuid)) {
                                return (
                                    <div key={uuid}>
                                        <div>
                                            {ICON['wenjianjia']}
                                            {tableName}
                                        </div>
                                        {children.length !== 0 && (
                                            <div>
                                                {children.map(({ uuid, tableName }) => (
                                                    <div
                                                        key={uuid}
                                                        onClick={() => {
                                                            setOptionsCall({
                                                                type: 'TableList',
                                                                data: {
                                                                    type: 'securitySlopeLeft',
                                                                    title: `${tableName}详情`,
                                                                    uuid,
                                                                },
                                                            })
                                                        }}
                                                    >
                                                        {tableName}
                                                    </div>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                )
                            } else return false
                        })}
                    </div>
                ) : (
                    <Empty />
                )
            ) : (
                <Spin />
            )}

            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}
